import React, { useState, useRef, useEffect } from 'react';
import { message, DatePicker, Form, Select, Divider, Layout, Tag, Tabs } from 'antd';
import PageHeader from '../components/PageHeader';
import type { FormInstance } from 'antd/lib/form';
import moment from 'moment';
import DynamicForm from '../components/DynamicForm';
import FloatCard from '../components/FloatCard';
import type { FormConfig } from '../components/DynamicForm';
import SelectedFilterTags from '../components/SelectedFilterTags';
import ListTable from '../components/ListTable';
import type { ListTableColumn } from '../components/ListTable';
import { Button } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import UserFormModal from './UserFormModal';
import SidebarMenu from '../components/SidebarMenu';
import RemoteSelect from '../components/RemoteSelect';
const { Content } = Layout;
import FilterForm from '../components/FilterForm'; // 引入FilterForm组件
import DemoPage from './DemoPage';
/**
 * 自定义日期范围选择器组件
 * 左侧选择年/月类型，右侧显示对应日期选择器
 */
interface CustomDateRange {
  type: 'year' | 'month';
  value: string;
}

interface CustomDateRangeSelectorProps {
  formValues: {
    customDateRange?: CustomDateRange | null;
  } | null;
}
// 自定义表单项组件
const CustomDateRangeSelector: React.FC<CustomDateRangeSelectorProps> = ({ formValues }) => {
  // 使用useState管理选择器的值和类型
  const [dateType, setDateType] = useState<'year' | 'month'>('year');
  const [selectedDate, setSelectedDate] = useState<moment.Moment | null>(null);

  // 获取表单实例
  const form = Form.useFormInstance();

  // 当选择的值变化时，同步到表单中
  useEffect(() => {
    if (form) {
      const valueToSet = selectedDate ? {
        type: dateType,
        value: selectedDate.format(dateType === 'year' ? 'YYYY' : 'YYYY-MM')
      } : null;
      form.setFieldValue('customDateRange', valueToSet);
    }
  }, [dateType, selectedDate, form]);

  // 监听表单值变化，实现从表单到组件的反向同步
  useEffect(() => {
    if (formValues && formValues.customDateRange) {
      const customDateRange = formValues.customDateRange;
      // 只有当表单值与当前组件状态不同时才更新
      if (customDateRange && customDateRange.type && customDateRange.type !== dateType) {
        setDateType(customDateRange.type);
      }
      if (customDateRange && customDateRange.value &&
        (!selectedDate || selectedDate.format(customDateRange.type === 'year' ? 'YYYY' : 'YYYY-MM') !== customDateRange.value)) {
        setSelectedDate(moment(customDateRange.value));
      }
    }
  }, []);

  return (
    <div style={{ width: '100%', display: 'flex', alignItems: 'center', gap: '12px' }}>
      {/* 左侧类型选择下拉框 */}
      <Select
        value={dateType}
        onChange={(value) => {
          setDateType(value);
          setSelectedDate(null); // 切换类型时重置日期
        }}
        style={{ width: '100px' }}
        options={[
          { label: '按年', value: 'year' },
          { label: '按月', value: 'month' }
        ]}
      />

      {/* 右侧日期选择器 */}
      <DatePicker
        picker={dateType}
        value={selectedDate}
        style={{ flex: 1 }}
        onChange={(date) => setSelectedDate(date)}
        // style={{ width: 'auto' }}
        placeholder={dateType === 'year' ? '选择年份' : '选择月份'}
      />
    </div>
  );
};

interface CustomRemoteSelectorProps {
  formValues: Record<string, unknown> | null;
}

const CustomRemoteSelector: React.FC<CustomRemoteSelectorProps> = ({ formValues }) => {
  // 获取表单实例
  const form = Form.useFormInstance();
  const [multiple, setMultiple] = useState(false);
  const [debounceTime, setDebounceTime] = useState(300);
  const [pageSize, setPageSize] = useState(10);
  const [selectedValue, setSelectedValue] = useState<any>(null);

  const fetchData = async (params: Record<string, any>) => {
    console.log('fetchData params:', params);
    const { current = 1, pageSize = 10, keyword = '' } = params;

    const url = new URL('http://uno.demo.genee.cn/uniadmin/api/group/1/user');
    url.searchParams.append('id', '1');
    url.searchParams.append('type', 'user');
    url.searchParams.append('current_page', current.toString());
    url.searchParams.append('page_size', pageSize.toString());

    if (keyword) {
      url.searchParams.append('name', keyword);
    }

    try {
      const response = await fetch(url.toString(), {
        method: 'GET',
        headers: {
          'x-gapper-oauth-token': 'TkjGwJxhAObfsLG1QIw87DrvqaonNwMSjCln1Y4o'
        }
      });

      if (!response.ok) {
        throw new Error('网络请求失败');
      }

      const result = await response.json();
      const data = result.content || [];
      const total = result.count || 0;
      const hasMore = (current * pageSize) < total;

      return {
        data: data.map((item: UserData) => {
          return { label: item.name, value: item.id }
        }), total, hasMore
      };
    } catch (error) {
      console.error('请求出错:', error);
      return { data: [], total: 0, hasMore: false };
    }
  }
  useEffect(() => {
    if (form) {
      form.setFieldValue('selectRemote', selectedValue);
    }
  }, [selectedValue, form]);

  // 回显
  useEffect(() => {
    if (formValues && formValues.selectRemote) {
      console.log('formValues.selectRemote:', formValues.selectRemote);
      const selectRemote = formValues.selectRemote;
      // 只有当表单值与当前组件状态不同时才更新
      if (selectRemote !== selectedValue) {
        setSelectedValue(selectRemote);
      }
    } else if (formValues && formValues.selectRemote === undefined) {
      // 当表单值变为undefined时（删除操作），清空内部状态
      setSelectedValue(null);
    }
  }, [formValues]);
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
      <RemoteSelect
        request={fetchData}
        debounceTime={debounceTime}
        pageSize={pageSize}
        onChange={(val: number | string | (number | string)[]) => {
          console.log("value>>", val);
          setSelectedValue(val);
          // form.setFieldValue('selectRemote', val);
        }}
        antdSelectProps={{
          style: { width: '100%' },
          placeholder: '请输入关键词搜索...',
          allowClear: true,
          mode: multiple ? 'multiple' : undefined,
          value: selectedValue,
        }}
      />
    </div>
  );
};
// 定义数据类型接口
interface UserData {
  id: string;
  name: string;
  age: number;
  address: string;
  status: 'active' | 'inactive' | 'pending';
  role: 'admin' | 'user' | 'guest';
}

// 模拟数据
const mockData: UserData[] = [
  { id: '1', name: '张三', age: 28, address: '北京市朝阳区', status: 'active', role: 'admin' },
  { id: '2', name: '李四', age: 32, address: '上海市浦东新区', status: 'inactive', role: 'user' },
  { id: '3', name: '王五', age: 45, address: '广州市天河区', status: 'pending', role: 'user' },
  { id: '4', name: '赵六', age: 36, address: '深圳市南山区', status: 'active', role: 'guest' },
  { id: '5', name: '钱七', age: 22, address: '杭州市西湖区', status: 'active', role: 'user' },
];

/**
 * 合并了表单和列表功能的页面组件
 */
const DemoCombinedPage: React.FC = () => {
  const [formValues, setFormValues] = useState<Record<string, unknown> | null>(null);
  const [selectedValues, setSelectedValues] = useState<Record<string, unknown> | null>(null);
  const [searchParams, setSearchParams] = useState<Record<string, unknown>>({});
  // 控制新增用户弹窗的显示状态
  const [isAddModalVisible, setIsAddModalVisible] = useState(false);
  // 创建表单实例，用于清空特定字段
  const formRef = useRef<FormInstance>(Form.useForm()[0]);
  // 管理表单折叠状态
  const [isFormCollapsed, setIsFormCollapsed] = useState(true);
  // 侧边栏折叠状态
  const [sidebarCollapsed, setSidebarCollapsed] = useState(false);


  // 模拟API请求
  const mockRequest = async (params: any): Promise<{ data: UserData[]; success: boolean; total: number }> => {
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 500));

    // 合并外部搜索参数和内部分页参数
    const combinedParams = { ...searchParams, ...params };

    // 模拟分页
    const pageSize = combinedParams.pageSize || 10;
    const currentPage = combinedParams.page || 1;
    const startIndex = (currentPage - 1) * pageSize;
    const endIndex = startIndex + pageSize;

    // 模拟搜索
    let filteredData = [...mockData];
    if (combinedParams.username) {
      filteredData = filteredData.filter(item => item.name.includes(combinedParams.username as string));
    }
    if (combinedParams.status) {
      filteredData = filteredData.filter(item => item.status === combinedParams.status);
    }
    if (combinedParams.role) {
      filteredData = filteredData.filter(item => item.role === combinedParams.role);
    }
    if (combinedParams.age) {
      filteredData = filteredData.filter(item => item.age === combinedParams.age);
    }

    // 返回结果
    return {
      data: filteredData.slice(startIndex, endIndex),
      success: true,
      total: filteredData.length,
    };
  };

  // 处理表单提交
  const handleSubmit = (values: any) => {
    message.success('搜索成功');
    setFormValues(values); // 更新当前提交的表单值

    // 将非空的表单值同步到selectedValues状态中
    const nonEmptyValues: Record<string, unknown> = {};
    Object.entries(values).forEach(([key, value]) => {
      // 过滤掉undefined、null、空字符串、空数组等无效值
      if (value !== undefined && value !== null &&
        (typeof value !== 'string' || value.trim() !== '') &&
        (!Array.isArray(value) || value.length > 0) &&
        (!value || typeof value !== 'object' || Object.keys(value).length > 0)) {
        nonEmptyValues[key] = value;
      }
    });

    setSelectedValues(nonEmptyValues);
    setSearchParams(nonEmptyValues); // 设置搜索参数，影响表格数据
  };

  const handleRemoveCondition = (fieldName: string) => {
    // 更新selectedValues状态
    setSelectedValues((prev) => {
      if (!prev) return null;
      const newSelectedValues = { ...prev };
      delete newSelectedValues[fieldName];
      return Object.keys(newSelectedValues).length > 0 ? newSelectedValues : null;
    });

    // 更新搜索参数
    setSearchParams((prev) => {
      const newSearchParams = { ...prev };
      delete newSearchParams[fieldName];
      return newSearchParams;
    });

    // 更新formValues状态
    setFormValues((prev) => {
      if (!prev) return null;
      const newFormValues = { ...prev };
      newFormValues[fieldName] = undefined;
      return newFormValues;
    });

    // 清空对应的表单字段
    if (formRef.current) {
      formRef.current.setFieldValue(fieldName, undefined);
    }
  };

  // 处理表单重置
  const handleReset = () => {
    message.success('表单已重置');
    if (formRef.current) {
      formRef.current.resetFields();
    }
    setFormValues(null);
    setSelectedValues(null);
    setSearchParams({});
  };

  // 处理表单折叠状态变化
  const handleCollapseChange = (collapsed: boolean) => {
    setIsFormCollapsed(collapsed);
  };

  // 处理编辑
  const handleEdit = (record: UserData) => {
    message.info(`编辑用户: ${record.name}`);
    // 这里可以实现编辑逻辑
  };

  // 处理删除
  const handleDelete = (id: string) => {
    message.info(`删除用户ID: ${id}`);
    // 这里可以实现删除逻辑
  };

  // 处理新增用户
  const handleAddUser = () => {
    setIsAddModalVisible(true);
  };

  // 处理新增用户成功
  const handleAddUserSuccess = (data: Record<string, unknown>) => {
    console.log('新增用户成功:', data);
    // 这里可以添加刷新表格数据等逻辑
    message.success('用户新增成功');
  };

  // 自定义工具栏
  const toolBarRender = () => [
    <Button key="add" type="primary" icon={<PlusOutlined />} onClick={handleAddUser}>
      新增
    </Button>,
    <Button key="batch-delete" danger>
      批量删除
    </Button>,
  ];

  // 新增用户弹窗组件
  const renderUserFormModal = () => (
    <UserFormModal
      visible={isAddModalVisible}
      onCancel={() => setIsAddModalVisible(false)}
      onSuccess={handleAddUserSuccess}
    />
  );

  // 定义表格列配置
  const columns: ListTableColumn<UserData>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
      hideInSearch: true,
      sorter: {

      },
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      width: 100,
      formItemProps: {
        type: 'text',
        props: {
          placeholder: '请输入姓名',
        },
        rules: [{ required: false, message: '请输入姓名' }],
      },
    },
    {
      title: '年龄',
      dataIndex: 'age',
      key: 'age',
      formItemProps: {
        type: 'number',
        props: { min: 0, max: 150 },
      },
      render: (text: number) => {
        if (text === undefined || text === null) return '-';
        if (text > 30) return <Tag color="red">{text}</Tag>;
        return <Tag color="blue">{text}</Tag>;
      },
    },
    {
      title: '地址',
      dataIndex: 'address',
      key: 'address',
      hideInSearch: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      valueEnum: {
        options: [
          { label: '活跃', value: 'active' },
          { label: '非活跃', value: 'inactive' },
          { label: '待审核', value: 'pending' },
        ],
      },
      formItemProps: {
        type: 'select',
      },
    },
    {
      title: '角色',
      dataIndex: 'role',
      key: 'role',
      valueEnum: {
        admin: { label: '管理员' },
        user: { label: '普通用户' },
        guest: { label: '访客' },
      },
      formItemProps: {
        type: 'select',
      },
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      render: (_, record) => (
        <>
          <Button type="link" style={{ color: 'var(--primary-color)', fontSize: '14px' }} icon={<EditOutlined />} size="small" onClick={() => handleEdit(record)}>
            编辑
          </Button>
          <Button type="link" danger icon={<DeleteOutlined />} size="small" onClick={() => handleDelete(record.id)}>
            删除
          </Button>
        </>
      ),
      hideInSearch: true,
    },
  ];

  // 模拟数据：省份和城市的级联选择数据
  const cascaderOptions = [
    {
      value: 'beijing',
      label: '北京',
      children: [
        { value: 'chaoyang', label: '朝阳区' },
        { value: 'haidian', label: '海淀区' },
        { value: 'dongcheng', label: '东城区' },
      ],
    },
    {
      value: 'shanghai',
      label: '上海',
      children: [
        { value: 'pudong', label: '浦东新区' },
        { value: 'xuhui', label: '徐汇区' },
        { value: 'jingan', label: '静安区' },
      ],
    },
    {
      value: 'guangdong',
      label: '广东',
      children: [
        { value: 'guangzhou', label: '广州' },
        { value: 'shenzhen', label: '深圳' },
        { value: 'dongguan', label: '东莞' },
      ],
    },
  ];

  // 模拟数据：用户角色选项
  const roleOptions = [
    { label: '管理员', value: 'admin' },
    { label: '普通用户', value: 'user' },
    { label: '访客', value: 'guest' },
  ];

  // 模拟数据：用户兴趣选项
  const interestOptions = [
    { label: '阅读', value: 'reading' },
    { label: '旅游', value: 'traveling' },
    { label: '运动', value: 'sports' },
    { label: '音乐', value: 'music' },
    { label: '编程', value: 'programming' },
    { label: '打篮球', value: 'basketball' },
    { label: '踢足球', value: 'football' },
  ];

  // 模拟数据：性别选项
  const genderOptions = [
    { label: '男', value: 'male' },
    { label: '女', value: 'female' },
    { label: '其他', value: 'other' },
  ];
  const handleValuesChange = (values: Record<string, unknown>) => {
    console.log('Form values changed:', values); // 打印表单值变化
  };
  // 定义表单配置（移到组件内部，确保能随状态变化更新）
  // 使用useMemo确保formConfig随着apiOptions的变化而重新生成
  const formConfig: FormConfig = React.useMemo(() => ({
    items: [
      // 基本信息部分
      {
        label: '邮箱',
        name: 'email',
        type: 'text',
        props: {
          placeholder: '请输入邮箱地址',
        },
      },
      {
        label: '手机号',
        name: 'phone',
        type: 'text',
        props: {
          placeholder: '请输入手机号码',
          maxLength: 11,
        },
        rules: [
          { required: false, message: '请输入手机号码' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码' },
        ],
      },
      {
        label: '性别',
        name: 'gender',
        type: 'radio',
        options: genderOptions,
        props: {
          buttonStyle: 'solid',
        },
      },
      {
        label: '自定义组件',
        name: 'selectRemote',
        type: 'custom',
        customRender: (
          // <RemoteSelectDemo />
          <CustomRemoteSelector formValues={formValues} />
        ),
      },
      // 更多信息部分（将被折叠）
      {
        label: '年龄',
        name: 'age',
        type: 'number',
        props: {
          placeholder: '请输入年龄',
          min: 18,
          max: 120,
          style: { width: '100%' },
        },
      },
      {
        label: '角色',
        name: 'role',
        type: 'select',
        options: roleOptions,
        props: {
          placeholder: '请选择用户角色',
          allowClear: true,
        },
      },
      {
        label: '出生日期',
        name: 'birthdate',
        type: 'date',
        props: {
          placeholder: '请选择出生日期',
          style: { width: '100%' },
          format: 'YYYY-MM-DD', // 日期格式
        },
      },
      {
        label: '居住地址',
        name: 'address',
        type: 'cascader',
        options: cascaderOptions,
        props: {
          placeholder: '请选择省/市',
          style: { width: '100%' },
        },
      },
      {
        label: '个人简介',
        name: 'bio',
        type: 'text',
        props: {
          placeholder: '请输入个人简介',
          rows: 4,
          maxLength: 200,
          showCount: true,
        },
      },
      {
        label: '兴趣爱好',
        name: 'interests',
        type: 'checkbox',
        options: interestOptions,
        // wrapperCol: { span: 16 }, // 自定义组件字段占满整行
        // labelCol: { span: 3 },
        props: {
          mode: 'multiple',
        },
      },
      {
        label: '自定义组件',
        name: 'customDateRange',
        type: 'custom',
        customRender: (
          <CustomDateRangeSelector formValues={formValues} />
        ),
      },
    ],
    onSubmit: handleSubmit,
    onReset: handleReset,
    layout: 'horizontal', // 标签对齐方式
    labelWidth: 280,
    collapsed: isFormCollapsed, // 使用状态管理折叠
    defaultShowCount: 2, // 默认显示前2个字段
    submitText: '搜索',
    resetText: '重置表单',
    form: formRef.current,
    onCollapseChange: handleCollapseChange, // 添加折叠状态变化回调
    itemsPerRow: 3, // 配置每行显示4个表单项
    onValuesChange: handleValuesChange, // 添加表单值变化回调
    // labelCol: { flex:'100px' }, // 标签列宽度
    actionColSpan: 8, // 操作按钮列宽度，默认为6
    // wrapperCol: { span: 16 }, // 表单项列宽度
  }), [isFormCollapsed]);

  return (
    <Layout style={{ minHeight: '100vh' }}>
      {/* 侧边栏 */}
      <SidebarMenu
        selectedKeys={['users', 'users-list']}
        onSelect={(keys) => {
          console.log('Selected menu keys:', keys);
          // 这里可以添加路由跳转逻辑
        }}
      />

      {/* 主内容区域 */}
      <Layout style={{ marginLeft: sidebarCollapsed ? 80 : 256, transition: 'margin-left 0.3s', background: '#FFF' }}>
        <Content style={{ minHeight: '100vh' }}>
          <div className="demo-combined-page">
            <PageHeader />
            <div style={{ padding: '0 20px' }}>
              <div style={{ fontSize: '20px', fontWeight: 'bold', color: '#333333', padding: '24px 0 4px' }}>
                UNO Demo
              </div>
              <Tabs
                defaultActiveKey="1"
                items={[
                  {
                    label: `正常仪器`,
                    key: '1',
                  },
                  {
                    label: `使用中仪器`,
                    key: '2',
                  },
                  {
                    label: `维保仪器`,
                    key: '3',
                  },
                  {
                    label: `故障仪器`,
                    key: '4',
                  },
                  {
                    label: `废弃仪器`,
                    key: '5',
                  }
                ]}
              />
              {/* 表单部分 */}
              <FilterForm isFloating={!formConfig.collapsed} formConfig={formConfig}></FilterForm>
              {/* 列表部分 */}
              <ListTable
                tableTitle={
                  <div style={{ fontSize: '16px', color: '#333333', fontWeight: 'bold' }}>总数 5个</div>// 自定义表格标题
                } // 自定义表格标题
                columns={columns}
                request={mockRequest}
                toolBarRender={toolBarRender}
                pagination={{
                  pageSize: 10,
                  showSizeChanger: true,
                  showQuickJumper: true,
                }}
                rowSelection={{
                  // 可以添加行选择功能
                }}
              />
              {/* 新增用户弹窗 */}
              {renderUserFormModal()}
            </div>
          </div>
        </Content>

      </Layout>
    </Layout>
  );
};

export default DemoCombinedPage;